<?php

namespace control;

/*
*任务列表类
*/


class missionClass extends adIndexClass
{
    private const title = '任务列表';
    private const page = 'mission';
    private const table = 'mission';
    private const table_child = 'mission_child';
    private const table_relation = 'mission_relation';
    private const table_record = 'mission_record';
    private const stateOption = ['未开始', '进行中', '已完成'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '任务编号',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'workFlow' => [
                        'name'  => "状态",
                        'width' => 100,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                    ],
                    'stid'         => [
                        'name'  => '发起人',
                        'width' => 200,
                    ],
                    'collaborator'          => [
                        'name'  => '协作人',
                        'width' => 200,
                    ],
                    'list'          => [
                        'name'  => '优先级',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'startTime'          => [
                        'name'  => '开始时间',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'endTime'          => [
                        'name'  => '截止时间',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'isOverdue'          => [
                        'name'  => '是否超期',
                        'width' => 150,
                    ],
                    'projectId'          => [
                        'name'  => '所属项目',
                        'width' => 150,
                    ],
                    'time'          => [
                        'name'  => '创建时间',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        //生成查询表单
        /*if ($workFlow == '我负责的') {
            $itherHtml = text(array("name" => "application", "title" => "借阅用途"));
        } else {
            $itherHtml = select(array("name" => "state", "title" => "审批状态", "option" => self::stateOption));
        }*/
        return $this->tableShow([
            [
                [
                    "任务编号" => text(array("name" => "orderNo")),
                    "状态"   => select(array("name" => "workFlow", "option" => self::stateOption)),
                    '标题' => text(array("name" => "title")),
                ],
                [
                    '发起人'  => selectMultiple(array("name" => "stid", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name')),
                    "优先级" => select(array("name" => "level", "option" => explode('，', para('missionList')))),
                    '截止时间' => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('我负责的');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*我负责的*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//借阅人单位
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'workFlow' => $this->post('workFlow'),
            "stid" => $this->post('stid'),
            "level" => $this->post('level'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "endTime");
        }
        if (!$this->power(self::page, 'seeAll')) {
            $and .= " and manager = '" . self::$stid . "'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'follow' => $array['manager'] == self::$stid ? array("title" => "反馈", "click" => "layer('" . self::page . "','workFlow',{id:'" . $array['id'] . "'})") : [],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "workFlow":
                        $row[] = $this->workFlowStyle($array['workFlow']);
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case "collaborator":
                        $row[] = self::findStaff(explode(',', $array['collaborator']));
                        break;
                    case "isOverdue":
                        $isOverdue = $array['workFlow'] != '已完成' ? (strtotime($array['endTime']) < time() ? "<span class='red'>是</span>" : '否') : (strtotime($array['endTime']) < strtotime($array['completeTime']) ? "<span class='red'>是</span>" : '否');
                        $row[] = $isOverdue;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function workFlowStyle($workFlow): string
    {
        return match ($workFlow) {
            '未开始' => "<span class='spanButton' style='background-color: #EC808D;color: white;border: none'>{$workFlow}</span>",
            '进行中' => "<span class='spanButton' style='background-color: #F59A23;color: white;border: none'>{$workFlow}</span>",
            '已完成' => "<span class='spanButton' style='background-color: #00B83F;color: white;border: none'>{$workFlow}</span>",
            default => $workFlow,
        };
    }

    /*列表页-查询条件*/
    public function tellMissionOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('知会我的');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 知会我的
     * @return string
     */
    public function tellMission(): string
    {
        $html = $this->tellMissionOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*知会我的*/
    public function tellMissionSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//借阅人单位
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'workFlow' => $this->post('workFlow'),
            "stid" => $this->post('stid'),
            "level" => $this->post('level'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "endTime");
        }
        if (!$this->power('tellMission', 'seeAll')) {
            $and .= " and notifier like '%" . self::$stid . "%'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "workFlow":
                        $row[] = $this->workFlowStyle($array['workFlow']);
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case "collaborator":
                        $row[] = self::findStaff(explode(',', $array['collaborator']));
                        break;
                    case "isOverdue":
                        $isOverdue = $array['workFlow'] != '已完成' ? (strtotime($array['endTime']) < time() ? "<span class='red'>是</span>" : '否') : (strtotime($array['endTime']) < strtotime($array['completeTime']) ? "<span class='red'>是</span>" : '否');
                        $row[] = $isOverdue;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function joinMissionOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('我参与的');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 知会我的
     * @return string
     */
    public function joinMission(): string
    {
        $html = $this->joinMissionOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function joinMissionSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//借阅人单位
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'workFlow' => $this->post('workFlow'),
            "stid" => $this->post('stid'),
            "level" => $this->post('level'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "endTime");
        }
        if (!$this->power('joinMission', 'seeAll')) {
            $and .= " and collaborator like '%" . self::$stid . "%'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "workFlow":
                        $row[] = $this->workFlowStyle($array['workFlow']);
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case "collaborator":
                        $row[] = self::findStaff(explode(',', $array['collaborator']));
                        break;
                    case "isOverdue":
                        $isOverdue = $array['workFlow'] != '已完成' ? (strtotime($array['endTime']) < time() ? "<span class='red'>是</span>" : '否') : (strtotime($array['endTime']) < strtotime($array['completeTime']) ? "<span class='red'>是</span>" : '否');
                        $row[] = $isOverdue;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function startMissionOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('我发起的');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 知会我的
     * @return string
     */
    public function startMission(): string
    {
        $html = $this->startMissionOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        if ($this->power('startMission', "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power('startMission', "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 我发起的
     * @return bool|string
     */
    public function startMissionSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//借阅人单位
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'workFlow' => $this->post('workFlow'),
            "stid" => $this->post('stid'),
            "level" => $this->post('level'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "endTime");
        }
        if (!$this->power('startMission', 'seeAll')) {
            $and .= " and stid = '" . self::$stid . "'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("startForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                "edit" => $array['workFlow'] != '未开始' ? [] : array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "workFlow":
                        $row[] = $this->workFlowStyle($array['workFlow']);
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case "collaborator":
                        $row[] = self::findStaff(explode(',', $array['collaborator']));
                        break;
                    case "isOverdue":
                        $isOverdue = $array['workFlow'] != '已完成' ? (strtotime($array['endTime']) < time() ? "<span class='red'>是</span>" : '否') : (strtotime($array['endTime']) < strtotime($array['completeTime']) ? "<span class='red'>是</span>" : '否');
                        $row[] = $isOverdue;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='startForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        /*****子任务*********/
        $childTr[] = ['', '标题', '负责人', '开始时间', '截止时间'];
        $result = find(array(
            'field' => "id as childId,childTitle,childManager,childStartTime,childEndTinme",
            'table' => self::table_child . " where orderId = '{$info['id']}' order by list asc"
        ));
        if (count($result['array']) > 0) {
            foreach ($result['array'] as $k => $array) {
                $array['list'] = $k + 1;
                $childTr[]          = $this->childRow($array);
            }
        } else {
            $childTr[] = $this->childRow(['childId' => self::getId(), 'list' => 1]);
        }
        /*****关联任务*********/
        $relationTr[] = ['', '任务', '负责人', '开始时间', '截止时间'];
        $result = find(array(
            'field' => "id as relationId,missionId",
            'table' => self::table_relation . " where orderId = '{$info['id']}' order by list asc"
        ));
        if (count($result['array']) > 0) {
            foreach ($result['array'] as $k => $array) {
                $mx = query(self::table, "id = '$array[missionId]'");
                $array['manager-span'] = self::findStaff($mx['manager']);
                $array['startTime-span'] = $mx['startTime'];
                $array['endTime-span'] = $mx['endTime'];
                $array['list'] = $k + 1;
                $relationTr[]          = $this->relationRow($array);
            }
        } else {
            $relationTr[] = $this->relationRow(['relationId' => self::getId(), 'list' => 1]);
        }
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "标题：" => text(["name" => "title", "value" => $info['title']]),
                    must . "负责人：" => selectMultiple(["name" => "manager", 'title' => '请选择', 'table' => 'staff', 'where' => "state !='离职'", 'sqlId' => 'stid', 'sqlField' => 'name', "value" => $info['manager']]),
                    "协作人：" => selectMultiple(["name" => "collaborator[]", 'title' => '请选择', 'multiple' => true, 'table' => 'staff', 'where' => "state !='离职'", 'sqlId' => 'stid', 'sqlField' => 'name', "value" => $info['collaborator']]),
                    "知会人：" => selectMultiple(["name" => "notifier[]", 'title' => '请选择', 'multiple' => true, 'table' => 'staff', 'where' => "state !='离职'", 'sqlId' => 'stid', 'sqlField' => 'name', "value" => $info['notifier']]),
                ],
                [
                    "开始时间：" => text(["name" => "startTime", 'laydate' => ['type' => 'datetime'], "value" => $info['startTime']]),
                    "截止时间：" => text(["name" => "endTime", 'laydate' => ['type' => 'datetime'], "value" => $info['endTime']]),
                    "优先级：" => select(["name" => "list", 'title' => '优先级', 'option' => explode('，', para('missionList')), "value" => $info['list']]),
//                    "所属项目：" => select(["name" => "projectId", 'title' => '所属项目', 'option' => [], "value" => $info['projectId']]),
                ],
                [
                    '描述' => textarea(array('name' => 'description', 'value' => $info['description']))
                ],
            ]
        ]);
        $body .= $this->editList([
            'title' => '子任务',
            'html' => $this->listTable(array('tr' => $childTr, 'end' => true)),
        ]);
        $body .= $this->editList([
            'title' => '关联任务',
            'html' => $this->listTable(array('tr' => $relationTr, 'end' => true)),
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($id, '任务管理', self::page, self::page . 'EditForm')
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        //返回
        return $this->tab($data) . $this->editJs();
    }


    /**
     * 进度反馈
     */
    public function workFlow(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "状态：" => select(array("name" => "workFlow", "title" => "状态", "option" => self::stateOption)),
            ),
            array(
                must . '备注：' => textarea(array('name' => 'text', 'class' => 'text'))
            ),
            array(
                '附件：' => fileUploadClass::addFileComponent(self::getId(), '任务反馈', self::page, self::page . 'WorkFlowForm')
            )
        ), 'hidden' => hidden(array('name' => 'missionId', 'value' => $this->post('id')))));
        //返回
        return $this->layer(array("title" => "反馈", "height" => 500, "width" => 800, "html" => $html));
    }

    /**
     * 进度反馈编辑
     */
    public function workFlowEdit(): bool|string
    {
        $missionId = $this->post('missionId');
        $field = array(
            'stid' => self::$stid,
            'id' => self::getId(),
            'orderId' => $missionId,
            'toState' => $this->post('workFlow'),
            'text' => $this->post('text'),
        );
        $annotation = [
            'orderId' => '任务ID',
            'toState' => '状态',
            'text' => '备注',
        ];
        $rules = [
            'orderId' => 'required',
            'toState' => 'required',
            'text' => 'required',
        ];
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        $info = query(self::table, "id = '$missionId'");
        if (empty($info['id'])) {
            $json['warn'] = "未找到此任务";
        } elseif ($info['workFlow'] == $field['toState']) {
            $json['warn'] = '未更改此任务状态';
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            $this->startTrans();
            $field['fromState'] = $info['workFlow'];
            $json['warn'] = static::insert(array(
                'table' => self::table_record,
                'field' => $field
            ));
            $completeTime = $field['toState'] == '已完成' ? $this->time : '';
            $warn = static::update(array('table' => self::table, 'field' => ['workFlow' => $field['toState'], 'completeTime' => $completeTime], 'where' => "id = '$info[id]'"));
            if ($warn != '更新成功') {
                $json['warn'] = $warn;
            }
            if (in_array($json['warn'], ['新增成功', '更新成功'])) {
                $this->commitTrans();
                $fileIdArr = $this->post('fileId');
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $field['id']], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $text = $this->control['name'] . "添加了一条任务反馈,状态：【{$field['toState']}】,备注 ：【" . $field['text'] . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                $_SESSION['warn'] = "修改成功";
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }
        //返回
        return json_encode($json, 320);
    }


    public function editJs(): string
    {
        return <<<eof
        <script>
        //添加一行
         function addRow(e,type){
             let id = $("[name='id']").val();
             $.post(root+'control/adIndex.html?cla=mission&fun=addRow',{type:type,id:id},function (res){
                $(e).closest('tr').after(res.data);
                resetNumber($(e).closest('tbody'))
             },'json');
         }
         function getMission(e){
             let missionId = e.value;
             $.post(root+'control/adIndex.html?cla=mission&fun=getMission',{missionId:missionId},function (res){
                 $(e).parent().parent().parent().find(".manager-span").html(res.manager);
                 $(e).parent().parent().parent().find(".startTime-span").html(res.startTime);
                 $(e).parent().parent().parent().find(".endTime-span").html(res.endTime);
             },'json');
         }
        </script>
eof;

    }

    /**
     * 获取此任务信息
     */
    public function getMission(): bool|string
    {
        $info = query(self::table, "id = '" . $this->post('missionId') . "'");
        $json = [
            'manager' => self::findStaff($info['manager']),
            'startTime' => $info['startTime'],
            'endTime' => $info['endTime'],
        ];
        return json_encode($json, 320);
    }

    /**
     * Desc : 子任务
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function childRow($data = [])
    {
        $list       = isset($data['list']) ? $data['list'] : '';
        $childId       = isset($data['childId']) && $data['childId'] ? $data['childId'] : self::getId();
        $field = ['childTitle','childManager','childStartTime','childEndTinme'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'childRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr         = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this,'child')"),
            hidden(array('name' => 'childId[]', 'value' => $childId)) .
            text(array('name' => 'childTitle[]', 'title' => '标题', 'value' => $array['childTitle'])),
            selectMultiple(["name" => "childManager[]", 'title' => '负责人', 'table' => 'staff', 'where' => "state !='离职'", 'sqlId' => 'stid', 'sqlField' => 'name', 'value' => $array['childManager']]),
            text(array('name' => 'childStartTime[]', 'laydate' => ['type' => 'datetime'], 'title' => '开始时间', 'value' => $array['childStartTime'])),
            text(array('name' => 'childEndTinme[]', 'laydate' => ['type' => 'datetime'], 'title' => '截止时间', 'value' => $array['childEndTinme'])),
        ];
        if ($data) {
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     * Desc : 关联任务
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function relationRow($data = [])
    {
        $list       = isset($data['list']) ? $data['list'] : '';
        $relationId       = isset($data['relationId']) && $data['relationId'] ? $data['relationId'] : self::getId();
        $field = ['missionId','manager-span','startTime-span','endTime-span'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'relationRow',
            'copy' => ['missionId'],
            'nodeTextByClass' => ['manager-span','startTime-span','endTime-span'],
        ],320);
        $delArg = json_encode([
            'empty' => ['missionId'],
            'emptyByClass' => ['manager-span','startTime-span','endTime-span'],
        ],320);
        $tr         = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this,'relation')"),
            hidden(array('name' => 'relationId[]', 'value' => $relationId)) .
            selectMultiple(["name" => "missionId[]", 'change' => 'getMission', 'title' => '任务', 'table' => self::table, 'where' => "workFlow !='已完成'", 'sqlId' => 'id', 'sqlField' => 'title', "value" => $array['missionId']]),
            "<span class='manager-span'>" . $array['manager-span'] . "</span>",
            "<span class='startTime-span'>{$array['startTime-span']}</span>",
            "<span class='endTime-span'>{$array['endTime-span']}</span>",
        ];
        if ($data) {
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $type = $this->post('type');
        $id = $this->post('id');
        $html = '';
        switch ($type) {
            case 'child':
                $res          = json_decode($this->childRow(), true);
                $html         = $res['html'];
                break;
            case 'relation':
                $res          = json_decode($this->relationRow(), true);
                $html         = $res['html'];
                break;
        }
        $json['data'] = $html;
        return json_encode($json, 320);
    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $childIdArr = $this->post('childId') ?: [];
        $childTitleArr = $this->post('childTitle');
        $childManagerArr = $this->post('childManager');
        $childStartTimeArr = $this->post('childStartTime');
        $childEndTinmeArr = $this->post('childEndTinme');
        $relationIdArr = $this->post('relationId') ?: [];
        $missionIdArr = $this->post('missionId');

        $field = [
            'title' => $this->post('title'),
            'manager' => $this->post('manager'),
            'collaborator' => $this->post('collaborator') ? implode(',', $this->post('collaborator')) : '',
            'notifier' => $this->post('notifier') ? implode(',', $this->post('notifier')) : '',
            'startTime' => $this->post('startTime'),
            'endTime' => $this->post('endTime'),
            'list' => $this->post('list'),
            'projectId' => $this->post('projectId'),
            'description' => $this->post('description'),
        ];
        $annotation = [
            'title' => '标题',
            'manager' => '负责人',
        ];
        $rules = [
            'title' => 'required',
            'manager' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power('startMission', "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
            $this->startTrans();
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'T',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'workFlow' => '未开始',
                    'stid' => self::$stid,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (is_array($childIdArr)) {
                foreach ($childIdArr as $k => $childId) {
                    $childField = [
                        'childTitle' => $childTitleArr[$k],
                        'childManager' => $childManagerArr[$k],
                        'childStartTime' => $childStartTimeArr[$k],
                        'childEndTinme' => $childEndTinmeArr[$k],
                    ];
                    $mx = query(self::table_child, "id = '$childId'");
                    if(empty(array_filter($childField, 'strlen'))) {
                        if (!empty($mx['id'])) delete(array('table' => self::table_child, 'where' => "id = '$childId'"));
                        continue;
                    }
                    if (empty($mx['id'])) {
                        $warn = static::insert(array(
                            'table' => self::table_child,
                            'field' => array_merge($childField, [
                                'id'      => $childId,
                                'orderId' => $id,
                            ])
                        ));
                    } else {
                        $warn = static::update(array(
                            'table' => self::table_child,
                            'field' => $childField,
                            'where' => "id = '$mx[id]'"
                        ));
                    }
                    if (!in_array($warn, ["新增成功", "更新成功"])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            if (is_array($relationIdArr)) {
                foreach ($relationIdArr as $k => $relationId) {
                    $relationField = [
                        'missionId' => $missionIdArr[$k],
                    ];
                    $mx = query(self::table_relation, "id = '$relationId'");
                    if(empty(array_filter($relationField, 'strlen'))) {
                        if (!empty($mx['id'])) delete(array('table' => self::table_relation, 'where' => "id = '$relationId'"));
                        continue;
                    }
                    if (empty($mx['id'])) {
                        $warn = static::insert(array(
                            'table' => self::table_relation,
                            'field' => array_merge($relationField, [
                                'id'      => $relationId,
                                'orderId' => $id,
                            ])
                        ));
                    } else {
                        $warn = static::update(array(
                            'table' => self::table_relation,
                            'field' => $relationField,
                            'where' => "id = '$mx[id]'"
                        ));
                    }
                    if (!in_array($warn, ["新增成功", "更新成功"])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::table_child, 'where' => " id not in ('" . implode("','", $childIdArr) . "') and orderId = '$id'"));
                delete(array('table' => self::table_relation, 'where' => " id not in ('" . implode("','", $relationIdArr) . "') and orderId = '$id'"));
                //添加主表ID到附件表
                $fileIdArr = $this->post('fileId');
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => 'startMission', "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*客户管理-客户详情页*/
    public function detail()
    {
        $info = query(self::table, "id = '" . $this->get('id') . "'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $childTr[] = ['标题', '负责人', '开始时间', '截止时间'];
            $result = find(array('table' => self::table_child, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $childTr[] = [
                    $array['childTitle'],
                    self::findStaff($array['childManager']),
                    $array['childStartTime'],
                    $array['childEndTinme'],
                ];
            }
            $relationTr[] = ['任务', '负责人', '开始时间', '截止时间'];
            $result = find(array('table' => self::table_relation, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $mission = query(self::table, "id = '$array[missionId]'");
                $relationTr[] = [
                    $mission['title'],
                    self::findStaff($mission['manager']),
                    $mission['startTime'],
                    $mission['endTime'],
                ];
            }
            $progressTr[] = ['变更人', '变更时间', '变更前状态', '变更后状态', '反馈内容', '附件名称'];
            $result = find(array('table' => self::table_record, 'where' => "orderId = '$info[id]' order by time desc"));
            foreach ($result['array'] as $array) {
                $num = static::total(array('table' => 'file', 'where' => "targetId = '" . $array['id'] . "'"));
                $fileBtn = $num > 0 ? "<span class='link' onclick=\"layer('component','fileDetail',{id:'" . $array['id'] . "'})\">" . $num . "</span>" : '';
                $progressTr[] = [
                    self::findStaff($array['stid']),
                    $array['time'],
                    $array['fromState'],
                    $array['toState'],
                    $array['text'],
                    $fileBtn
                ];
            }
            //按钮
            $button = [];

            if ($this->power('startMission', "edit") && $info['workFlow'] == '未开始' && $info['stid'] == self::$stid) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑",
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                ];
            }
            if ($this->power('startMission', "del") && $info['workFlow'] == '未开始' && $info['stid'] == self::$stid) {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            if ($info['manager'] == self::$stid) {
                $button[] = [
                    "name" => "进度反馈",
                    "type" => "点击事件",
                    "title" => "进度反馈",
                    "fun" => "layer('" . self::page . "','workFlow',{id:'" . $info['id'] . "'})",
                    'style' => 'li-btn-blue-bg',
                ];
            }

            //审核按钮
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                 "详细信息" => array(
                    array(
                        "标题" => $info['title'],
                        "负责人" => self::findStaff($info['manager']),
                        "协作人" => self::findStaff(explode(',', $info['collaborator'])),
                        "知会人" => self::findStaff(explode(',', $info['notifier'])),
                    ),
                    array(
                        "开始时间" => $info['startTime'],
                        "截止时间" => $info['endTime'],
                        "优先级" => $info['list'],
//                        '所属项目'=>$info['projectId']
                    ),
                    array(
                        "描述" => pre($info['description']),
                    )
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '子任务',
                'html' => $this->listTable(array('tr' => $childTr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '关联任务',
                'html' => $this->listTable(array('tr' => $relationTr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], '任务管理'),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '任务进度',
                'html' => $this->listTable(array('tr' => $progressTr, 'showSort' => true)),
            ]);
            $data['html']   .= $this->tableShow(array(
                '系统信息' => array(
                    array(
                        "创建人" => self::findStaff($info['stid']),
                        '创建时间' => $info['time'],
                        "状态" => $info['workFlow'],
                    )
                )
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, startForm';
                $power = '';
                break;
        }
        if (!$this->power('startMission', $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power('startMission', "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id'");
                if ($info['workFlow'] != '未开始') {
                    //返回
                    $warn = "删除失败：不是未开始状态";
                } else {
                    $all = find(array('table' => "file", "where" => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                    }
                    $recordAll = find(array('table' => self::table_record, 'where' => "orderId = '$id'"));
                    foreach ($recordAll['array'] as $record) {
                        $all = find(array('table' => "file", "where" => "targetId = '$record[id]'"));
                        foreach ($all['array'] as $val) {
                            fileDelete($val['src']);
                        }
                        delete(array("table" => 'file', "where" => " targetId = '$record[id]' "));
                    }
                    //删除附件
                    delete(array("table" => 'file', "where" => " targetId = '$id' "));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::table_relation, "where" => " orderId = '$id' "));
                    delete(array("table" => self::table_child, "where" => " orderId = '$id' "));
                    delete(array("table" => self::table_record, "where" => " orderId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            if ($text) {
                $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
                $this->logText(array("type" => 'startMission', "text" => $text));
            }
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
